<%@ page language="java" contentType="text/html; charset=UTF-8"
		 pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
	<base href="<%=basePath %>"><!-- 整个页面全部指定为这个地址 -->
	<meta charset="UTF-8">
	<title>用户增加或修改页面</title>
	<link rel="stylesheet" href="res/js/layui/css/layui.css" media="all">
	<script src="res/js/jquery-3.4.1.min.js" type="text/javascript"
			charset="utf-8"></script>
	<script src="res/js/layui/layui.js" charset="utf-8"></script>
	<script src="res/js/Tools.js"></script>
	<script type="text/javascript">
        //全局同步
        $.ajaxSetup({
            async : false
        });
	</script>
	<style type="text/css">
		.layui-form-label {
			width: 70px;
		}

		.layui-input-block {
			width: 70%;
		}

		body {
			padding-top: 5px;
		}
	</style>
</head>
<body>
<form class="layui-form" action="" id="formDId" lay-filter="example" method="post" enctype="multipart/form-data">
	<input type='hidden' name='userId' id='userId'>
	<input type="hidden" name="userImg" id="userImg">
	<input type="hidden" name="oneName" id="oneName">
	<input type='hidden' name='oneState'id="oneState">
	<input type="hidden" name="onechaId" id="onechaId">
	<div class="layui-form-item">
		<label class="layui-form-label">用户名</label>
		<div class="layui-input-block">
			<input type="text" name="userName" lay-verify="title" required  lay-verify="required" autocomplete="off" placeholder="请输入标题" class="layui-input" id="userName">
		</div>
	</div>
	<div class="layui-form-item">
		<label class="layui-form-label">用户密码</label>
		<div class="layui-input-block">
			<input type="password" name="userPassword" required  lay-verify="required"  Maxlength="20"  id="userPassword" placeholder="请输入密码" autocomplete="off" class="layui-input">
		</div>
	</div>
	<div class="layui-form-item">
		<label class="layui-form-label">手机号</label>
		<div class="layui-input-block">
			<input type="text" name="userPhone" required lay-verify="required|phone" id="userPhone" lay-verify="title" autocomplete="off" placeholder="请输入手机号" class="layui-input">
		</div>
	</div>
	<div class="layui-form-item">
		<label class="layui-form-label">邮箱</label>
		<div class="layui-input-block">
			<input type="text" name="userEmail" required lay-verify="email" Maxlength="20" id="userEmail" lay-verify="title" autocomplete="off" placeholder="请输入邮箱" class="layui-input">
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label">职位</label>
		<div class="layui-input-block" id="checkBox">
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label">是否有效</label>
		<div class="layui-input-block">
			<input type="checkbox" checked="" name="userState" id="userState" lay-skin="switch" lay-filter="switchTest" lay-text="有效|无效">
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label">用户图片</label>
		<div class="layui-input-block">
			<input type="file" name="userdImg"/>
		</div>
	</div>

	<div class="layui-form-item">
		<div class="layui-input-block">
			<button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
			<button type="reset" class="layui-btn layui-btn-primary">重置</button>
		</div>
	</div>
</form>
<script type="text/javascript">
    function conveterParamsToJson(paramsAndValues) {
        var jsonObj = {};

        var param = paramsAndValues.split("&");
        for ( var i = 0; param != null && i < param.length; i++) {
            var para = param[i].split("=");
            jsonObj[para[0]] = para[1];
        }

        return jsonObj;
    }
    /**
     * 将表单数据封装为json
     * @param form
     * @returns
     */
    function getFormData(form) {
        var formValues = $("#" + form).serialize();

        //关于jquery的serialize方法转换空格为+号的解决方法
        formValues = formValues.replace(/\+/g," ");   // g表示对整个字符串中符合条件的都进行替换
        var temp =  decodeURIComponent(JSON.stringify(conveterParamsToJson(formValues)));
        var queryParam = JSON.parse(temp);
        return queryParam;
    }
    var form=null;
    layui.use('form', function(){
        form = layui.form;
        //监听提交
        form.on('submit(formDemo)', function(data){
            var c=data.field.userName;
            var url1="userController/findName.action";
            var userId= $("#userId").val();
            var data1={userName:c,userId:userId};
            var hd=c;
            var cot=hd.length;
            $.post(url1,data1,function(obj){
                if(cot>20){
                    layer.msg("用户名字不能超过20个!!!!!!");
                    return false;
				}
                if(obj.state==1){
                    layer.msg(obj.msg);
                    return false;
                }else{
                    var id = "";
                    var cb="";
                    $("input[name='chaId']:checked").each(function(index,items){
                        id+=$(this).val()+",";
                    });
                    var userState=data.field.userState;
                    if (userState == null || userState == undefined || userState == '') {
                        cb=0;
                    }else{
                        cb=1;
                    }
                    var userState=data.field.userState=c;
                    var chaId=data.field.chaId=id;
                    $("#onechaId").val(id);
                    $("#oneState").val(cb);
                    $("#oneName").val($("#userName").val());
                    var formData = new FormData(document.getElementById("formDId"));
                    var url = "userController/insert.action";
                    $.ajax({
                        url:url,
                        type:"post",
                        data:formData,
                        processData:false,
                        contentType:false,
                        dataType:"json",
                        success:function(obj){
                            if(obj.state==1){
                                layer.msg("成功！",{
                                    icon:1,
                                    time:1000,
                                },function(){
                                    //关闭当前层
                                    //当你在iframe页面关闭自身时
                                    var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                                    parent.layer.close(index); //再执行关闭
                                });
                                return false ;
                            }
                        },
                        error:function(e){
                            alert("操作错误！");
                        }
                    });
                    // $.post(url,data.field,function(obj){
                    //     if(obj.state==1){
                    //         layer.msg("成功！",{
                    //             icon:1,
                    //             time:1000,
                    //         },function(){
                    //             //关闭当前层
                    //             //当你在iframe页面关闭自身时
                    //             var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                    //             parent.layer.close(index); //再执行关闭
                    //         });
                    //         return false ;
                    //     }
                    // },"json");
                    return false;
                }
            },"json");
            return false;//提交失败不会刷新表单数据
        });
        var ide = getQueryString("id");

        if(ide!=null){
            findById();//修改页面的赋值
        }else{
            var url = 'userController/findJueseAll.action';
            $.post(url,null,function(obj){
                $.each(obj,function(index,items){
                    $("#checkBox").append('<input type="checkbox" name="chaId" title="'+items.chaName+'" value="'+items.chaId+'">');
                    form.render("checkbox");
                })
            },'json');
        }
        //修改页面的赋值
        function findById(){
            var id=getQueryString("id");
            $('#userName').prop("disabled", true);//禁止输入；
            $("#userName").attr("onfocus", "this.blur()");
            $("#userName").css("background", "#CCCCCC");
            $("#userName").css("cursor", "not-allowed");
            var url="userController/findByIdThree.action";
            var data={userId:id};
            $.post(url,data,function(obj){
                var chaId = obj.chaId ;
                var ids = chaId.split(',');
                var urlone = 'userController/findJueseAll.action';
                $.post(urlone,null,function(objs){
                    $.each(objs,function(index,item){
                        var j = 0;
                        for (var i = 0; i < ids.length; i++) {
                            if(item.chaId==ids[i]){
                                j=1;
                                break ;
                            }
                        }
                        if(j==1){
                            $("#checkBox").append('<input type="checkbox" name="chaId" checked="checked" title="'+item.chaName+'" value="'+item.chaId+'">');
                            form.render("checkbox");
                        }else if(j==0){
                            $("#checkBox").append('<input type="checkbox" name="chaId" title="'+item.chaName+'" value="'+item.chaId+'">');
                            form.render("checkbox");
                        }
                    })
                },"json");
                for (var i = 0; i < ids.length; i++) {
                    $("#chaId").prop("LAY_CHECKED:",true);
                }
                $("#userId").val(obj.userId);
                $("#userPassword").val(obj.userPassword);
                $("#userName").val(obj.userName);
                $("#userPhone").val(obj.userPhone);
                $("#userEmail").val(obj.userEmail);
                $("#userImg").val(obj.userImg);
                if(obj.userState=="1"){
                    form.val('example', {
                        "userState": true //开关状态
                    })
                }else{
                    form.val('example', {
                        "userState": false //开关状态
                    })
                }
                //form.render('select');
            },"json");
        }
    });
</script>
</body>
</html>